class StaffsController < ApplicationController
  include ControllerHelper
  before_filter :require_admin
  def new
    set_form_settings
    @page["name"] = "staff"
    @staff = Staff.new
    render :layout => "form"
  end

  def create
    begin
      @staff = Staff.new(params[:staff])
      if @staff.save
        redirect_to staff_admin_path(:status => "all") and return
      else
        set_form_settings
        @page["name"] = "staff"
        render :action => "new", :layout => "form"
      end
    rescue
      flash[:notice] = I18n.t "site.message.corrupted_html"
      set_form_settings
      @page["name"] = "staff"
      render :action => "new", :layout => "form"
    end
  end

  def admin
    per_page = params[:per_page] ||= @site["per_page"]["admin"]["staffs"]
    conditions = []
    conditions = merge_conditions(conditions, ["status = ?", "approved"]) if params[:status] == "approved"
    conditions = merge_conditions(conditions, ["status <> ?", "approved"]) if params[:status] == "banned"
    @staffs = Staff.find(:all, :conditions => conditions, :order => :shop_id).uniq.paginate(:page => params[:page], :per_page => per_page)
    set_admin_settings
    render :layout => "cms"
  end

  def destroy
    @staff = Staff.find(:first, :conditions => ["id = ?", params[:id]])
    if @staff
      @staff.destroy
    else
      flash[:notice] = I18n.t "site.message.no_staff"
    end
    redirect_to staff_admin_path(:status => "all")
  end

  def edit
    set_form_settings
    @page["name"] = "staff"
    @staff = Staff.find(:first, :conditions => ["id = ?", params[:id]])
    if @staff.nil?
      flash[:notice] = I18n.t "site.message.no_staff"
      redirect_to staff_admin_path(:status => "all") and return
    else
      render :layout => "form"
    end
  end

  def update
    @staff = Staff.find(:first, :conditions => ["id = ?", params[:id]])
    if @staff.nil?
      flash[:notice] = I18n.t "site.message.no_staff"
      redirect_to staff_admin_path(:status => "all") and return
    else
      if @staff.update_attributes(params[:staff])
        redirect_to staff_admin_path(:status => "all") and return
      else
        set_form_settings
        @page["name"] = "staff"
        render :layout => "form", :action => "edit", :id => params[:id]
      end
    end
  end

  def approve_ban
    staff = Staff.find(params[:id])
    old_status = staff.status == "approved" ? "approved" : "banned"
    staff.status = staff.status == "approved" ? "banned" : "approved"
    staff.save
    redirect_to staff_admin_path(:status => old_status)
  end

end
